#include "opedb.h"
#include <QMessageBox>
#include <QDebug>

OpeDB::OpeDB(QObject *parent)
    : QObject{parent}
{
    m_db = QSqlDatabase::addDatabase("QSQLITE");
}

OpeDB &OpeDB::getinstance()
{
    static OpeDB instance;
    return instance;
}

void OpeDB::init()
{
    m_db.setHostName("localhost");
    m_db.setDatabaseName("D:\\Desktop\\Documents\\code\\qt_code\\TCP_Server\\TcpServer\\cloud.db");
    if (m_db.open())
    {
        QSqlQuery query;
        query.exec("select * from usrInfo");
        while(query.next()){
            QString data = QString("%1,%2,%3").arg(query.value(0).toString(),query.value(1).toString()
                                                   ,query.value(3).toString());
        }
    }
    else
    {
        QMessageBox::critical(NULL,"open database","open database failed");
    }

}

bool OpeDB::handleRegist(const char *name, const char *pwd)
{
    if(NULL==name||NULL==pwd){
        return false;
    }
    QString data = QString("insert into usrInfo(name,pwd) values('%1','%2')").arg(name,pwd);
    QSqlQuery query;
    return query.exec(data);
}

bool OpeDB::handleLogin(const char *name, const char *pwd)
{
    if(NULL==name||NULL==pwd){
        return false;
    }
    QString data = QString("select * from usrInfo where name = \'%1\' and pwd = \'%2\'and online=0").arg(name,pwd);
    QSqlQuery query;
    qDebug()<<data;
    query.exec(data);
    if(query.next()){
        data = QString("update usrInfo set online=1  where name = \'%1\' and pwd = \'%2\'").arg(name,pwd);
        QSqlQuery query;
        qDebug()<<data;
        query.exec(data);
        return true;
    }else {
        return false;
    }
}

void OpeDB::handleOffline(const char *name)
{
    if(NULL==name){
    }
    QString data = QString("update usrInfo set online=0  where name = \'%1\' ").arg(name);
    QSqlQuery query;
    qDebug()<<data;
    query.exec(data);
}

int OpeDB::handleSearchUsr(const char *name)
{
    if(NULL==name){
        return -1;
    }
    QString data = QString("select online from usrInfo where name = \'%1\'").arg(name);
    QSqlQuery query;
    query.exec(data);
    qDebug()<<data;
    if(query.next()){
        int ret = query.value(0).toInt();
        if(1 == ret){
            return 1;
        }else if(0 == ret){
            return 0;
        }
    }else{
        return -1;
    }
}

QStringList OpeDB::handleAllOnline()
{
    QString data = QString("select name from usrInfo where online=1");
    QSqlQuery query;
    query.exec(data);
    QStringList result;
    result.clear();
    while(query.next()){
        result.append(query.value(0).toString());

    }
    return result;
}
